package com.caishi.lkx.course.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.caishi.lkx.course.mapper.VideoChapterMapper;
import com.caishi.lkx.course.mapper.VideoInfoMapper;
import com.caishi.lkx.course.model.VideoChapterModel;
import com.caishi.lkx.course.model.VideoInfoModel;
import com.caishi.lkx.course.service.IVideoChapterService;
import com.zzw.common.entity.IBaseMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.concurrent.atomic.AtomicReference;

import static com.zzw.common.cache.CacheConstants.BIG_UP_UP;


@Service
public class VideoChapterServiceImpl  implements IVideoChapterService {

    @Resource
    private VideoChapterMapper videoChapterMapper;
    @Resource
    private VideoInfoMapper videoInfoMapper;


    @Override
    public IBaseMapper<VideoChapterModel, String> getMapper() {
        return videoChapterMapper;
    }

    @CacheEvict(value = BIG_UP_UP, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public VideoChapterModel insert(VideoChapterModel entity) {
        if (ObjectUtil.isNotEmpty(entity.getParentId()) && !entity.getParentId().equals("0")) {
            VideoChapterModel parent = getById(entity.getParentId());
            if (parent.getLeaf()) {
                parent.setLeaf(false);
                getMapper().updateById(parent);
            }
        }
        entity.setLeaf(true);
        updatePath(entity);
      return IVideoChapterService.super.insert(entity);
    }

    private void updatePath(VideoChapterModel entity) {
        if (StrUtil.isNotBlank(entity.getPath())) return;
        var parent = getById(entity.getParentId());
        String subPath;
        if (parent == null) {
            subPath = "";
        } else {
            String path = parent.getPath();
            if(StrUtil.isBlank(path)){
                subPath = parent.getId();
            }else{
                subPath = path + "/" + parent.getId();
            }

        }
        entity.setPath(subPath);
    }


    @Override
    @Transactional
    public void changeVideoCount(String id) {
        VideoChapterModel chapter = getById(id);
        chapter.setVideoNum(Math.toIntExact(videoInfoMapper.selectCount(Wrappers.<VideoInfoModel>lambdaQuery().eq(VideoInfoModel::getChapterId, id).eq(VideoInfoModel::getDeleted, false))));
        update(chapter);
        var parentIds =  chapter.getPath().split("/");
        //逐级更新上级视频数量
        for (int i = parentIds.length - 1; i >= 0; i--) {
            if(StrUtil.isNotBlank(parentIds[i])){
                AtomicReference<Integer> videoNum = new AtomicReference<>(0);
                allChildren(parentIds[i]).forEach(item->{
                    videoNum.updateAndGet(v -> v + item.getVideoNum());
                });
                VideoChapterModel parent = new VideoChapterModel();
                parent.setId(parentIds[i]);
                parent.setVideoNum(videoNum.get());
                update(parent);
            }

        }
    }
}
